package cn.ywang.pattern.singleton.register;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册式单例
 *
 * @author BeatificWang
 * @date 2019/3/10 17:18
 */
public class ContainerSingleton {

	private ContainerSingleton() {
	}

	private static final Map<String, Object> CONTAINER = new HashMap<>(2);

	/**
	 * 双重锁
	 *
	 * @param className
	 * @return
	 */
	public static Object getBean(String className) {
		Object object = null;
		if (CONTAINER.containsKey(className)) {
			object = CONTAINER.get(className);
		}
		else {
			synchronized (CONTAINER) {
				if (!CONTAINER.containsKey(className)) {
					try {
						object = Class.forName(className).newInstance();
						CONTAINER.put(className, object);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return object;
	}


}
